#
# Copyright (c) 2023 supercell
#
# SPDX-License-Identifier: BSD-3-Clause
#

module Luce
  # Matches autolinks like `<foo@bar.example.com>`.
  #
  # See <https://spec.commonmark.org/0.30/#email-address>.
  class EmailAutoLinkSyntax < InlineSyntax
    @email : String = %q{[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}} +
      %q{[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*}

    def initialize
      super("<(#{@email})>", start_character: Charcode::LT)
    end

    def on_match(parser : InlineParser, match : Regex::MatchData) : Bool
      url = match[1]
      text = parser.encode_html? ? HTML.escape(url) : url
      anchor = Element.text("a", text)
      anchor.attributes["href"] = DartURI.encode_full("mailto:#{url}")
      parser.add_node(anchor)

      true
    end
  end
end
